/**
 * dwrloader - jQuery EasyUI
 * 
 * Licensed under the GPL: http://www.gnu.org/licenses/gpl.txt
 * 
 * Copyright 2012 stworthy [ stworthy@gmail.com ]
 * 
 */
(function($) {
	/**
	 * get default json loader
	 */
	function getJsonLoader(pluginName) {
		return function(param, success, error) {
			var opts = $(this)[pluginName]('options');
			if (!opts.url)
				return false;
			$.ajax( {
				type : opts.method,
				url : opts.url,
				data : param,
				dataType : 'json',
				success : function(data) {
					success(data);
				},
				error : function() {
					error.apply(this, arguments);
				}
			});
		}
	}

	/**
	 * get dwr data loader 2013-08-14 modified by chensr，改成适应后台的方法接口
	 */
	function getDwrLoader(pluginName) {
		if (pluginName == "tree") {
			return treeDwrLoader(pluginName);
		}
		if (pluginName == "datagrid") {
			return datagridDwrLoader(pluginName);
		}

		return eval("$.fn." + pluginName + ".defaults.loader");
	}

	/**
	 * 树的dwr加载方法
	 */
	var treeDwrLoader = function(pluginName) {
		return function(param, success, error) {
			var opts = $(this)[pluginName]('options');
			if (!opts.url)
				return false;
			var dwrFunc = eval(opts.url);
			var treeType = opts.treeType || "syn";
			if (treeType == "asyn") {
				dwrFunc(param, {
					callback : function(data) {
						success(data);
					},
					exceptionHandler : function() {
						error.apply(this, arguments);
					}
				});
			} else {
				dwrFunc( {
					callback : function(data) {
						success(data);
					},
					exceptionHandler : function() {
						error.apply(this, arguments);
					}
				})
			}
		}
	}

	/**
	 * datagrid的dwr loader方法
	 */
	var datagridDwrLoader = function(pluginName) {
		return function(param, success, error) {
			var opts = $(this)[pluginName]('options');
			if (!opts.url)
				return false;
			var dwrFunc = eval(opts.url);
			// 页号
			var page = param.page || 1;
			// 页长
			var pagesize = param.rows || 10;

			var orderField = new Array();
			var condition = param.condition || null;
			var rowCount = true;
			// 排序的列
			var sort = param.sort || null;
			// 排序方式
			var order = param.order || null;
			// console.dir(param);
			if (order != null) {
				orderField.push(sort + " " + order)
			}
			orderField = orderField.length == 0 ? null : orderField;
			dwrFunc(page, pagesize, orderField, condition, rowCount, {
				callback : function(data) {
					success(data);
				},
				exceptionHandler : function() {
					error.apply(this, arguments);
				}
			});
		}
	}

	$.fn.combobox.defaults.loader = getDwrLoader('combobox');
	$.fn.tree.defaults.loader = getDwrLoader('tree');
	$.fn.treegrid.defaults.loader = getDwrLoader('treegrid');
	$.fn.datagrid.defaults.loader = getDwrLoader('datagrid');
})(jQuery);
